<?php
/**
 * http Request Base
 */

namespace request;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use request\Request;

class HttpRequest extends Client
{
    public function run(Request $request, $options = []) {
        $method = strtoupper($request->getMethod());
        try {
            $params = $request->getParams();
            if(!$method) $method = 'GET';

            $this->log($method, $request->getUrl());
            if(is_array($params)) {
                foreach($params as $key => $val) {
                    $this->log('Params', ' [ '.$key.' ] '. (is_scalar($val) ? $val : 'Array '. json_encode($val, JSON_UNESCAPED_UNICODE)));
                }
            } else {
                $this->log('Params', $params);
            }
            $result = http_request($request->getUrl(), $method, $params);

            $this->log('Result', $result);

            $request->setStatusCode(200);
            $request->setResponse($result);

        } catch (\Exception $e) {
            $this->log('Error', $e->getMessage());
            throw new \request\RequestException($e->getMessage());
        }

        return $request;
    }

    protected function log($type, $content) {
        !is_scalar($content) and $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        $content = date('Y-m-d H:i:s | ').$type.': '.$content;
        $content .= "\r\n";
        file_rput_contents(RUNTIME_PATH.'/http_log/'.date('Ym/d').'.log', $content, FILE_APPEND);
    }
}